#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <queue>
using std::cout;
using std::endl;
using std::queue;

const size_t tidNum = 2;
const size_t queue_size = 5;

class Blockqueue
{
public:
    ~Blockqueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);
    }
    bool isFull()
    {
        if (_capacity == queue_size)
            return true;
        return false;
    }

    bool isEmpty()
    {
        if (_capacity == 0)
            return true;
        return false;
    }
    void push(int &a)
    {
        pthread_mutex_lock(&_mutex);
        while (isFull())
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        cout << "生产者放数据:" << a << endl;
        _q.push(a);
        ++_capacity;
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_c_cond);
    }

    int pop()
    {
        pthread_mutex_lock(&_mutex);
        while (isEmpty())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        int x = _q.front();
        cout << "消费者拿数据：" << x << endl;
        _q.pop();
        --_capacity;

        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_p_cond);
        return x;
    };

private:
    queue<int> _q;
    int _capacity = 0;

    pthread_cond_t _c_cond = PTHREAD_COND_INITIALIZER; // 消费者 队列为空时
    pthread_cond_t _p_cond = PTHREAD_COND_INITIALIZER; // 生产者 队列为满时
    pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
};
